package org.dromara.wmscloud.service.impl;

import jakarta.annotation.Resource;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.wmscloud.common.IAsyncService;
import org.dromara.wmscloud.domain.vo.BaseLocationVo;
import org.dromara.wmscloud.domain.vo.BaseWarehouseVo;
import org.springframework.stereotype.Service;
import org.dromara.wmscloud.domain.bo.BaseUnitBo;
import org.dromara.wmscloud.domain.vo.BaseUnitVo;
import org.dromara.wmscloud.domain.BaseUnit;
import org.dromara.wmscloud.mapper.BaseUnitMapper;
import org.dromara.wmscloud.service.IBaseUnitService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 物料单位Service业务层处理
 *
 * @author hou
 * @date 2025-04-04
 */
@RequiredArgsConstructor
@Service
public class BaseUnitServiceImpl implements IBaseUnitService {

    private final BaseUnitMapper baseUnitMapper;


    /**
     * 查询物料单位
     *
     * @param unitId 主键
     * @return 物料单位
     */
    @Override
    public BaseUnitVo queryById(Long unitId){
        return baseUnitMapper.selectVoById(unitId);
    }

    /**
     * 分页查询物料单位列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 物料单位分页列表
     */
    @Override
    public TableDataInfo<BaseUnitVo> queryPageList(BaseUnitBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BaseUnit> lqw = buildQueryWrapper(bo);
        Page<BaseUnitVo> result = baseUnitMapper.selectVoPage(pageQuery.build(), lqw);
        List<BaseUnitVo> records = result.getRecords();
        if (records.isEmpty()) {
            return TableDataInfo.build(result);
        }

        // 1. 提取所有 primaryUnitId
        Set<Long> primaryUnitIds = records.stream()
            .map(BaseUnitVo::getPrimaryUnitId)
            .filter(Objects::nonNull)
            .collect(Collectors.toSet());
        // 如果 primaryUnitIds 为空，直接跳过 SQL 查询
        if (primaryUnitIds.isEmpty()) {
            return TableDataInfo.build(result);
        }
        // 2. 批量查询 UnitName 并转换为 Map
        Map<Long,String> unitIdNameMap = baseUnitMapper.selectPrimaryNamesByIds(primaryUnitIds)
            .stream()
            .collect(Collectors.toMap(BaseUnitVo::getUnitId, BaseUnitVo::getUnitName));

        // 3. 赋值 PrimaryUnitName，仅当 primaryUnitId 不为空时
        records.forEach(vo -> {
            Long primaryUnitId = vo.getPrimaryUnitId();
            if (primaryUnitId != null) {
                vo.setPrimaryUnitName(unitIdNameMap.get(primaryUnitId));
            }
        });

        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的物料单位列表
     *
     * @param bo 查询条件
     * @return 物料单位列表
     */
    @Override
    public List<BaseUnitVo> queryList(BaseUnitBo bo) {
        LambdaQueryWrapper<BaseUnit> lqw = buildQueryWrapper(bo);
        List<BaseUnitVo> list = baseUnitMapper.selectVoList(lqw);
        if (list.isEmpty()) {
            return list;
        }

        // 1. 提取所有 primaryUnitId
        Set<Long> primaryUnitIds = list.stream()
            .map(BaseUnitVo::getPrimaryUnitId)
            .filter(Objects::nonNull)
            .collect(Collectors.toSet());

        // 如果 primaryUnitIds 为空，直接跳过 SQL 查询
        if (primaryUnitIds.isEmpty()) {
            return list;
        }

        // 2. 批量查询 UnitName 并转换为 Map
        Map<Long,String> unitIdNameMap = baseUnitMapper.selectPrimaryNamesByIds(primaryUnitIds)
            .stream()
            .collect(Collectors.toMap(BaseUnitVo::getUnitId, BaseUnitVo::getUnitName));

        // 3. 赋值 PrimaryUnitName，仅当 primaryUnitId 不为空时
        list.forEach(vo -> {
            Long primaryUnitId = vo.getPrimaryUnitId();
            if (primaryUnitId != null) {
                vo.setPrimaryUnitName(unitIdNameMap.get(primaryUnitId));
            }
        });
        return list;
    }

    private LambdaQueryWrapper<BaseUnit> buildQueryWrapper(BaseUnitBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BaseUnit> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(BaseUnit::getUnitId);
        lqw.eq(StringUtils.isNotBlank(bo.getUnitCode()), BaseUnit::getUnitCode, bo.getUnitCode());
        lqw.like(StringUtils.isNotBlank(bo.getUnitName()), BaseUnit::getUnitName, bo.getUnitName());
        lqw.eq(StringUtils.isNotBlank(bo.getPrimaryFlag()), BaseUnit::getPrimaryFlag, bo.getPrimaryFlag());
        lqw.eq(bo.getPrimaryUnitId() != null, BaseUnit::getPrimaryUnitId, bo.getPrimaryUnitId());
        lqw.eq(bo.getChangeRate() != null, BaseUnit::getChangeRate, bo.getChangeRate());
        lqw.eq(bo.getStatus() != null, BaseUnit::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增物料单位
     *
     * @param bo 物料单位
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BaseUnitBo bo) {
        BaseUnit add = MapstructUtils.convert(bo, BaseUnit.class);
        validEntityBeforeSave(add);
        boolean flag = baseUnitMapper.insert(add) > 0;

        if (flag) {
            bo.setUnitId(add.getUnitId());
        }
        return flag;
    }

    /**
     * 修改物料单位
     *
     * @param bo 物料单位
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BaseUnitBo bo) {
        BaseUnit update = MapstructUtils.convert(bo, BaseUnit.class);
        validEntityBeforeSave(update);
        return  baseUnitMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BaseUnit entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除物料单位信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseUnitMapper.deleteByIds(ids) > 0;
    }
}
